package com.eqdd.yiqidian.ui.base;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.eqdd.annotation.api.DataInjector;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseMultiItemQuickAdapter;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.EditBean;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by lvzhihao on 17-3-24.
 */

public abstract class BaseMultiEditActivity extends BaseActivity {

    public List<EditBean> editBeans = new ArrayList<>();
    private RecyclerView recyclerView;
    private Map<Integer, ActionSheetDialog> bottomChooses = new HashMap<>();
    private Map<Integer, TimePickerView> pvDayTimes = new HashMap<>();
    private Map<Integer, TextView> editContents = new HashMap<>();
    public int clicked;
    public BaseMultiItemQuickAdapter<EditBean, BaseViewHolder> quickAdapter;
    public LinearLayoutManager mLinearLayoutManager;
    private AlertDialog alertDialog;
    public boolean isTip = true;
    public boolean isSaveData = true;

    public String getContentByPositon(int position) {
        return ((TextView) quickAdapter.getViewByPosition(position, R.id.tv_vertical_content)).getText().toString().trim();
    }


    @Override
    public void setView() {
        recyclerView = initRecyclerView();
        if (recyclerView == null) {
            System.out.println("recyclerView 未设置");
            return;
        }
        recoverData();
        mLinearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setFocusable(false);
        if (quickAdapter == null) {
            quickAdapter = new BaseMultiItemQuickAdapter<EditBean, BaseViewHolder>(editBeans) {
                @Override
                protected void convert(BaseViewHolder helper, EditBean item) {
                    switch (item.getItemType()) {
                        case EditBean.CONTENT:
                            helper.setVisible(R.id.ll_staff_records,item.isShow());
//                            View convertView = helper.getConvertView();
//                            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) convertView.getLayoutParams();
////获取当前控件的布局对象
//                            if (item.isShow()) {
//                                params.height = 60 * WindowUtil.csw / WindowUtil.width;//设置当前控件布局的高度
//                            } else {
//                                params.height = 0;
//                            }
//                            convertView.setLayoutParams(params);//将设置好的布局参数应用到控件中
                            TextView content = helper.getView(R.id.tv_vertical_content);
                            if (TextUtils.isEmpty(item.getContent())) {
                                content.setHint(item.getHint());
                                content.setText("");
                            } else {
                                content.setText(item.getContent());
                            }
                            helper.setText(R.id.tv_vertical_title, item.getTitle())
                                    .setVisible(R.id.iv_bottom, item.isBottom())
                                    .setVisible(R.id.iv_top, item.isTop())
                                    .setVisible(R.id.iv_line, item.isUnderLine());
                            helper.getView(R.id.iv_enter).setVisibility(item.isEnter() ? View.VISIBLE : View.INVISIBLE);
                            if (item.isShowTopTitle()) {
                                helper.setVisible(R.id.rl_top, true)
                                        .setVisible(R.id.tv_top_title, true)
                                        .setText(R.id.tv_top_title, item.getTopTitle());
                            }
                            switch (item.getType()) {
                                case 0:
                                case 4:
                                    editContents.put(item.getPosition() == -1 ? helper.getPosition() : item.getPosition(), helper.getView(R.id.tv_vertical_content));
                                    break;
                                case 1:
                                    bottomChooses.put(item.getPosition() == -1 ? helper.getPosition() : item.getPosition(),
                                            getBottomChoose(item.getChooseItem(), helper.getView(R.id.tv_vertical_content)));
                                    break;
                                case 2:
                                    pvDayTimes.put(item.getPosition() == -1 ? helper.getPosition() : item.getPosition(),
                                            getTimePicker(Config.YEAR_MONTH_DAY, helper.getView(R.id.tv_vertical_content)));
                                    break;
                                case 3:
                                    pvDayTimes.put(item.getPosition() == -1 ? helper.getPosition() : item.getPosition(),
                                            getTimePicker(Config.ALL, helper.getView(R.id.tv_vertical_content)));
                                    break;
                                case 5:
                                    pvDayTimes.put(item.getPosition() == -1 ? helper.getPosition() : item.getPosition(),
                                            getTimePicker(Config.HOUR_MINITE, helper.getView(R.id.tv_vertical_content)));
                                    break;

                            }
                            break;
                        case EditBean.TITLE:
                            helper.setVisible(R.id.rl_top, true)
                                    .setVisible(R.id.tv_top_title, true)
                                    .setText(R.id.tv_top_title, item.getTopTitle());
                            break;
                    }
                }
            };
            quickAdapter.addItemType(EditBean.TITLE, R.layout.item_edit_title_type);
            quickAdapter.addItemType(EditBean.CONTENT, R.layout.item_edit);
            quickAdapter.bindToRecyclerView(recyclerView);
            recyclerView.setAdapter(quickAdapter);
            ItemClickSupport.addTo(recyclerView).setOnItemClickListener(
                    (rv, p, v) -> {
                        if (quickAdapter.getItem(p).getItemType() == EditBean.TITLE)
                            return;
                        clicked = p;
                        int realPosition = quickAdapter.getItem(p).getPosition() == -1 ? p : quickAdapter.getItem(p).getPosition();
                        switch (quickAdapter.getItem(p).getType()) {
                            case 0:
                                Bundle bundle = new Bundle();
                                bundle.putString("content", editContents.get(realPosition).getText().toString());
                                bundle.putString("tip", quickAdapter.getItem(p).getTextTip());
                                bundle.putString("title", quickAdapter.getItem(p).getTextTitle());
                                AppConstent.schemes = quickAdapter.getItem(p).getSchemes();
                                startActivityForResult(EditTextActivity.class, bundle, p);
                                break;
                            case 1://选项选择器
                                bottomChooses.get(realPosition).show();
                                break;
                            case 2://日期选择期 日
                            case 3://日期选择期 日
                            case 5:
                                pvDayTimes.get(realPosition).show();
                                break;

                        }
                        itemClick(p);
                    }
            );
        }
        loadNet();
    }

    protected void loadNet() {

    }

    public void refresh() {
        quickAdapter.notifyDataSetChanged();
    }


    private TimePickerView getTimePicker(int type, TextView textView) {
        TimePickerView pvDayTime = new TimePickerView.Builder(this, (date, v) -> {
            SimpleDateFormat sf = null;
            switch (type) {
                case Config.YEAR_MONTH_DAY:
                    sf = new SimpleDateFormat("yyyy-MM-dd");
                    break;
                case Config.ALL:
                    sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    break;
                case Config.HOUR_MINITE:
                    sf = new SimpleDateFormat("HH:mm");
                    break;
            }
            textView.setText(sf.format(date));
            editBeans.get(clicked).setContent(sf.format(date));
        })
                .setOutSideCancelable(true)
                .setType(type == Config.YEAR_MONTH_DAY ? Config.YEAR_MONTH_DAY_TYPE : (type == Config.ALL ? Config.ALL_TYPE : Config.HOUR_MINITE_TYPE))
                .setDate(Calendar.getInstance())
                .setRange(1950, 2050)
                .build();
        return pvDayTime;
    }

    private ActionSheetDialog getBottomChoose(String[] chooseTexts, TextView textView) {
        ActionSheetDialog bottomChoose = ChooseAlertView.getBottomChoose(this, "请选择", chooseTexts,
                (ob, position) -> {
                    if (position >= 1 && position <= chooseTexts.length) {
                        textView.setText(chooseTexts[position - 1]);
                        quickAdapter.getItem(clicked).setContent(chooseTexts[position - 1]);
                        quickAdapter.notifyItemChanged(clicked);
                        onChooseClick(position);
                    }
                }
        );
        return bottomChoose;
    }

    public void onChooseClick(int position) {
    }


    protected abstract RecyclerView initRecyclerView();

    public abstract void itemClick(int p);


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Config.INTENT_CONTENT:
                System.out.println(data.getStringExtra("content"));
                editBeans.get(clicked).setContent(data.getStringExtra("content"));
                quickAdapter.notifyItemChanged(clicked);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (isTip) {
            isExitEdit();
        } else {
            super.onBackPressed();
        }
    }

    private void isExitEdit() {
        if (alertDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("你要退出此次编辑吗?");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", (dialog, which) -> {
                dialog.dismiss();
                finish();

            });
            builder.setNegativeButton("取消", (DialogInterface dialog, int which) -> {
                        dialog.dismiss();
                    }
            );
            alertDialog = builder.create();
        }
        alertDialog.show();
    }

    @Override
    public void onClick(View v) {
        if (isTip) {
            switch (v.getId()) {
                case R.id.back:
                    isExitEdit();
                    break;
                default:
                    super.onClick(v);
                    break;
            }
        } else {
            super.onClick(v);
        }
    }

    @Override
    protected void onDestroy() {
        if (isSaveData) {
            saveData();
        }
        super.onDestroy();
    }

    public void saveData() {
        if (editBeans != null) {
            SPUtil.setParam(getLocalClassName() + user.getUname(), editBeans);
        }
        DataInjector.saveData(this);
    }

    public void recoverData() {
        List<EditBean> data = (List<EditBean>) SPUtil.getParam(getLocalClassName() + user.getUname());
        if (data != null) {
            editBeans = data;
        }
    }

    public void clearData() {
        SPUtil.setParam(getLocalClassName() + user.getUname(), Config.NULL);
    }
}
